package ar.edu.caece.pl.main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

import ar.edu.caece.pl.asem.codegenerator.CodeGenerator;
import ar.edu.caece.pl.asem.model.INodeData;
import ar.edu.caece.pl.asem.model.tree.Tree;
import ar.edu.caece.pl.asin.manager.impl.AnalizadorSintactico;
import ar.edu.caece.pl.asin.model.ITokenStream;
import ar.edu.caece.pl.asin.model.impl.TokenStream;

public class Compilador {

	private static File file;

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		final JFrame frame = new JFrame("Compilador");

		JButton btnFile = new JButton("Abrir Codigo Fuente");
		btnFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final JFileChooser fc = new JFileChooser();
				int returnVal = fc.showOpenDialog(frame);
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					file = fc.getSelectedFile();
					System.out.println("File: " + file.getName() + ".");
					try {
						InputStream source = new FileInputStream(file.getAbsolutePath());

						// Comienza la ejecucion del analizador sintaxis
						ITokenStream tokenStream = new TokenStream(source);
						AnalizadorSintactico asin = new AnalizadorSintactico(
								tokenStream, true);
						boolean codigoValido = asin.reconocer();

						// Arbol generado
						if (codigoValido) {
							Tree<INodeData> semanticTree = new Tree<INodeData>();
							semanticTree.setRoot(asin.getTreeNode());
							CodeGenerator.getInstance().setTree(semanticTree);

							System.out
									.println("----------- Comienza la generacion del codigo -----------");
							System.out.println();
							String code = CodeGenerator.getInstance()
									.generateCode();

							PrintWriter writer = null;
							try {
								writer = new PrintWriter(file.getAbsolutePath() + ".asm",
										"UTF-8");
								writer.println(code);
								writer.close();
							} catch (UnsupportedEncodingException e1) {
								System.out
										.println("Error generando el archivo asm");
							}

						} else {
							asin.getErrorManager().getErrors();
						}

					} catch (FileNotFoundException e1) {
						System.out.println("No se encontro el codigo fuente");
					}
				} else {
					System.out.println("Se cancelo la accion por el usuario");
				}
			}
		});

		frame.getContentPane().add(btnFile);
		frame.setSize(300, 100);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}

}
